<template>
  <div class="component-upload-image">
    <el-upload
      action="#"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      name="file"
      :show-file-list="false"
      :headers="headers"
      style="display: flex; vertical-align: top"
      :http-request="requestUpload"
    >
      <el-image v-if="!tokenUrl" :src="tokenUrl">
        <div slot="error" class="image-slot">
          <i class="el-icon-plus" />
        </div>
      </el-image>
      <div v-else class="image">
        <video
          v-if="videoShow"
          :style="`width:100px;height:100px;object-fit:fill;`"
          :src="imgUrl"
          controls="controls"
        ></video>
        <el-image v-else :src="tokenUrl" :style="`width:100px;height:100px;`" fit="fill" />

        <div class="mask">
          <div class="actions">
            <span title="预览" @click.stop="dialogVisible = true" v-if="!videoShow">
              <i class="el-icon-zoom-in" />
            </span>
            <span title="移除" @click.stop="removeImage">
              <i class="el-icon-delete" />
            </span>
          </div>
        </div>
      </div>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip">
        照片要求:
        <div>
          1.请上传 <b style="color: #f56c6c">{{ fileType.join('/') }}格式图片</b>, 单个图片不超过
          <b style="color: #f56c6c">{{ fileSize }}KB</b>
        </div>
        <div> 2.logo尺寸不大于250*250 </div>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
      <img :src="tokenUrl" style="display: block; max-width: 100%; margin: 0 auto" />
    </el-dialog>
  </div>
</template>

<script>
  // import { getToken } from "@/utils/auth";
  import { apiPostUpload } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    props: {
      value: {
        type: String,
        default: ''
      },
      // 大小限制(KB)
      fileSize: {
        type: Number,
        default: 500
      },
      // 文件类型, 例如['png', 'jpg', 'jpeg','mp4']
      fileType: {
        type: Array,
        default: () => ['jpg', 'png']
      }
    },
    data() {
      return {
        dialogVisible: false,
        headers: {
          // Authorization: "Bearer " + getToken()
        },
        imgUrl: this.value,

        videoShow: false
      }
    },
    computed: {
      tokenUrl() {
        return this.imgUrl ? this.imgUrl.split('##')[0] : this.imgUrl
      }
    },
    watch: {
      value: {
        handler(val) {
          this.imgUrl = val
          this.getType(val)
        },
        immediate: true
      }
    },
    methods: {
      // 判断是video
      getType(imgUrl) {
        if (this.value) {
          const seat = imgUrl.split(',')[0].lastIndexOf('.') // 注意大小写
          const fileType = imgUrl.substring(seat).toLowerCase() // 扩展名jpg
          if (fileType == '.mp4') {
            this.videoShow = true
          }
        }
      },
      // 覆盖默认的上传行为
      requestUpload(params) {
        const formData = new FormData()
        formData.append('file', params.file, params.file.name || 'user_avatar.png')
        formData.append('businessCode', 2000)
        formData.append('fileName', params.file.name)
        apiPostUpload(formData).then(({ code, data }) => {
          if (code === EnumApiCode.Success) {
            this.imgUrl = data?.filePath ?? ''
          }
        })
      },
      removeImage() {
        this.imgUrl = ''
        this.$emit('input', '')
      },
      handleUploadSuccess(res) {
        // this.$emit("input", res.url);
        this.loading.close()
      },
      // handleBeforeUpload() {
      //   this.loading = this.$loading({
      //     lock: true,
      //     text: "上传中",
      //     background: "rgba(0, 0, 0, 0.7)"
      //   });
      // },
      handleUploadError() {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
        this.loading.close()
      },
      // 上传前校检格式和大小
      handleBeforeUpload(file) {
        // 校检文件类型
        if (this.fileType) {
          let fileExtension = ''
          if (file.name.lastIndexOf('.') > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
          }
          const isTypeOk = this.fileType.some((type) => {
            if (file.type.indexOf(type) > -1) return true
            if (fileExtension && fileExtension.indexOf(type) > -1) return true
            return false
          })
          if (!isTypeOk) {
            this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`)
            return false
          }
          // 格式正确，判断视频格式
          this.videoShow = ['mp4'].some((type) => {
            if (fileExtension && fileExtension.indexOf(type) > -1) return true
            return false
          })
        }

        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 < this.fileSize
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 ${this.fileSize} KB!`)
            return false
          }
        }
        return true
        // const reader = new FileReader()
        // reader.readAsDataURL(file)
        // reader.onload = () => {
        //   this.imgUrl = reader.result
        //   this.$emit('input', this.imgUrl, file)
        // }
      }
      // handleBeforeUpload(file) {
      //   if (file.type.indexOf("image/") == -1) {
      //     this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      //   } else {
      //     const reader = new FileReader();
      //     reader.readAsDataURL(file);
      //     reader.onload = () => {
      //       this.imgUrl = reader.result;
      //        this.getType(this.imgUrl);
      //       this.$emit("input", this.imgUrl, file);
      //     };
      //   }
      // }
    }
  }
</script>

<style scoped lang="scss">
  .image {
    position: relative;
    width: 100px;
    height: 100px;
    .mask {
      opacity: 0;
      position: absolute;
      top: 0;
      width: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      transition: all 0.3s;
    }
    &:hover .mask {
      opacity: 1;
    }
  }
  .el-upload__tip {
    margin-left: 20px;
  }
  ::v-deep .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
    background: rgba(237, 238, 240, 0.5);
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #c9ccd1;
  }
  ::v-deep .el-upload--picture-card i {
    font-size: 24px;
    color: #dee0e3;
  }
</style>
